const http=require('http');
const fs=require('fs');
const path=require('path');

let server=http.createServer((request,response)=>{
    showDir(request,response);
})

//绑定端口
server.listen(10011,()=>{
    console.log('服务器启动成功！');
});

//显示文件夹中的内容
function showDir(request,response) {
    //获取请求路径
    let url=request.url;

    // let dirPath='D:\\csddd';

    let dirPath='C:\\Program Files';

    if (request.url!='/favicon.ico') {
        response.end('timg.jpg')
    }else if (request.url != '/') {
            dirPath = request.url;
            dirPath = dirPath.substring(1, dirPath.length);
    }

    //读取文件夹
    fs.readdir(dirPath,(err,files)=>{
        //有异常，向外抛出
        if (err){
            throw err;
        }

        //拼接数据
        let data='';

        files.forEach(fileName=>{
            //拼接路径
            let joinPath=path.join(dirPath,fileName);

            //获取属性
            let stats=fs.statSync(joinPath);

            //如果是文件夹，拼接a标签
            if (stats.isDirectory()){
                data += `<li><a href="${joinPath}"> ${fileName}</a></li>`
            }else {
                //不是文件夹，不拼a标签
                data += `<li>${fileName}</li>`
            }
        })
        response.end(buildHtml(data));
    })
}

function buildHtml(data) {
    return `<!DOCTYPE html>
		<html lang="en">
		<head>
		    <meta charset="UTF-8">
		    <title>Title</title>
		    <style>
		    *{
		    padding: 0;
		    margin: 0;
		    }
		    
		    li{
		    list-style: none;
		    padding: 0.5em 1em;
		    background-color:#ddd;
		    border-top: 1px solid #eee;
		    }
		    
		    li:hover{
		    background-color:#aaa;
		    }
		</style>
		</head>
		<body>
		<ul>
		${data}
		</ul>
		</body>
		</html>`
}